package org.comidas;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.widget.Chronometer;
import android.widget.TextView;

public class CronometroActivity extends Activity {
	private TextView txtStatus;
	private RefreshHandler mRedrawHandler = new RefreshHandler();
	Chronometer cronometro;

	class RefreshHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			CronometroActivity.this.updateUI();
		}

		public void sleep(long delayMillis) {
			this.removeMessages(0);
			sendMessageDelayed(obtainMessage(0), delayMillis);
		}
	};

	private void updateUI() {
		// int currentInt = Integer.parseInt((String) txtStatus.getText()) + 10;
		// if(currentInt <= 100){
		// mRedrawHandler.sleep(1000);
		// txtStatus.setText(String.valueOf(currentInt));
		// }

		int stoppedMilliseconds = 0;

		String chronoText = cronometro.getText().toString();
		String array[] = chronoText.split(":");
		if (array.length == 2) {
			stoppedMilliseconds = Integer.parseInt(array[0]) * 60 * 1000
					+ Integer.parseInt(array[1]) * 1000;
		} else if (array.length == 3) {
			stoppedMilliseconds = Integer.parseInt(array[0]) * 60 * 60 * 1000
					+ Integer.parseInt(array[1]) * 60 * 1000
					+ Integer.parseInt(array[2]) * 1000;
		}

		cronometro.setBase(SystemClock.elapsedRealtime() - stoppedMilliseconds);
		cronometro.start();

	}

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		cronometro = new Chronometer(this);
		cronometro.setText("00:00:00");
		txtStatus = new TextView(this);
		txtStatus.setText(cronometro.getText().toString());
		setContentView(cronometro);

		updateUI();
	}
}